<script lang="ts" setup name="StoreHouseDialog">
import { FormInstance, FormRules } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { createStoreHouseAPI, editStoreHouseAPI } from '~/src/api/information'
import { Procure } from '~/src/api/interface/procure'

interface Params {
  visible: boolean
  title: string
  form: Procure.StoreHouse
}
const params = reactive<Params>({
  visible: false,
  form: {
    id: 0,
    isDefault: false,
    name: '',
    code: '',
  },
  title: '',
})

const { visible, title } = toRefs(params)
const putParams = async (data: Params) => {
  params.visible = data.visible
  params.form = cloneDeep(data.form)
  params.title = data.title
}
const emits = defineEmits<{
  (name: 'onConfirm', value: Procure.StoreHouse): void
}>()

const formRef = ref<FormInstance>()
const onConfirm = async () => {
  await formRef.value?.validate()
  if (params.form.id) {
    await editStoreHouseAPI(params.form)
  } else {
    await createStoreHouseAPI(params.form)
  }
  emits('onConfirm', params.form)
  params.visible = false
}
const rules: FormRules = {
  name: [{ required: true, message: '请输入仓库名称', trigger: ['blur'] }],
  code: [{ required: true, message: '请输入仓库编码', trigger: ['blur'] }],
}

watch(
  () => params.visible,
  (newV) => {
    if (!newV) formRef.value?.resetFields()
  }
)
defineExpose({
  putParams,
})
</script>

<template>
  <vab-dialog v-model:modelValue="visible" :title="title + '仓库'" :width="600">
    <el-form ref="formRef" label-suffix="：" label-width="130px" :model="params.form" :rules="rules">
      <el-form-item label="仓库编码" prop="code">
        <el-input v-model="params.form.code" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="仓库名称" prop="name">
        <el-input v-model="params.form.name" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="是否默认" prop="isDefault">
        <!-- <el-switch v-model="params.form.isDefault" /> -->
        <el-radio-group v-model="params.form.isDefault">
          <el-radio label="是" :value="true" />
          <el-radio label="否" :value="false" />
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="onConfirm">保存</el-button>
      <el-button @click="visible = false">取消</el-button>
    </template>
  </vab-dialog>
</template>

<style lang="scss" scoped></style>
